//===============================================================================
// Microsoft patterns & practices Enterprise Library Contribution
// Mapping Application Block
//===============================================================================

using System;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using EntLibContrib.Mapping.Configuration;
using EntLibContrib.Mapping.Properties;

namespace EntLibContrib.Mapping
{
	/// <summary>
	/// Represents a view to navigate the <see cref="MappingSettings"/> configuration data.
	/// </summary>
	public class MappingConfigurationView
	{
		#region Fields
		private IConfigurationSource configurationSource;
		#endregion

		#region Properties
		/// <summary>
		/// Gets the <see cref="MappingSettings"/> configuration data.
		/// </summary>
		/// <returns>
		/// The <see cref="MappingSettings"/> configuration data.
		/// </returns>
		[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
		public MappingSettings MappingSettings
		{
			get 
			{
				MappingSettings settings = MappingSettings.GetMappingSettings(configurationSource);
				if (settings == null)
					throw new ConfigurationErrorsException(InternalResources.MissingMappingSection);

				return settings;
			}
		}
		#endregion

		#region Construction
		/// <summary>
		/// Initialize a new instance of the <see cref="MappingConfigurationView"/> with an <see cref="IConfigurationSource"/>.
		/// </summary>
		/// <param name="configurationSource">An <see cref="IConfigurationSource"/> object.</param>
		public MappingConfigurationView(IConfigurationSource configurationSource)
		{
			if (configurationSource == null)
				throw new ArgumentNullException("configurationSource");

			this.configurationSource = configurationSource;
		}
		#endregion

		#region Public Methods
		/// <summary>
		/// Gets the <see cref="MapperBaseData"/> from configuration for the named <see cref="IMapper"/>
		/// </summary>
		/// <param name="mapperName">The name of the <see cref="IMapper"/>.</param>
		/// <returns>
		/// A <see cref="MapperBaseData"/> object.
		/// </returns>
		public MapperBaseData GetMapperData(string mapperName)
		{
			if (string.IsNullOrEmpty(mapperName))
				throw new ConfigurationErrorsException(InternalResources.ExceptionMapperNameNullOrEmpty);

			MappingSettings configSettings = this.MappingSettings;
			if (!configSettings.Mappers.Contains(mapperName))
				throw new ConfigurationErrorsException(string.Format(InternalResources.Culture, InternalResources.ExceptionProviderNotDefined, mapperName));

			return configSettings.Mappers.Get(mapperName);
		}
		#endregion
	}
}